<?php

namespace app\admin\controller;

use app\common\controller\AdminBase;
use think\App;
use util\Token;

/**
 * Tfrecord控制器
 */
class Tfrecord extends AdminBase
{

    protected $model = null;
    protected $token = null;

    protected $validate = null;
    protected $adminId = null;

    protected $relationSearch = false;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\Tfrecord();

        $this->validate = \app\admin\validate\Tfrecord::class;
        $this->token = $this->request->header('token');
        $this->adminId = Token::userId($this->token);
    }


    // //brand回传
    // public function tf_apply_brand()
    // {
    //     $brand = strtolower(input('brand'));
    //     //新品保护期 产品信息表设置新品保护期开始时间
    //     $time = table('product_info')->where(['brand' => $brand])->find();
    //     //新品时间
    //     $xp_time = !empty($time['xp_time']) ? $time['xp_time'] : 0;
    //     //爆品时间
    //     $bp_time = !empty($time['bp_time']) ? $time['bp_time'] : 0;
    //     //当前时间和新品保护期时间比较，大于则不可申请
    //     $xpend_time = strtotime('+3 month', $xp_time);
    //     $bpend_time = strtotime('+1 month', $bp_time);
    //     if (time() < $xpend_time) {
    //         return success('保护期,暂无法投放', []);
    //     }
    //     if (time() < $bpend_time) {
    //         return success('保护期,暂无法投放', []);
    //     }
    //     $time_where[] = ['start_time', '<=', time()];
    //     $time_where[] = ['end_time', '>=', time()];
    //     //查询投放表的投放人数  1 审核通过的总数
    //     $num = table('tfrecord')->where(['apply_status' => 1, 'tf_status' => 1, 'brand' => $brand])->where($time_where)->count();
    //     if ($num == 3 || $num > 3) {
    //         return success('投放人数已满,暂无法投放', []);
    //     }
    //     $row['brand'] = $brand;
    //     return success('ok', $row);
    // }


    public function index()
    {
        //判断是否是超管理,不是超管只能显示自己申请的数据
        list($limit, $where, $sortArr) = $this->buildTableParames();
        $is_superadmin = Token::is_superadmin($this->token);
        $where = [];
        if (!$is_superadmin) {
            $where[] = ['tf_admin',  '=', $this->adminId];
        }
        $filters = $this->request->get('filter', '{}');
        $filters = json_decode($filters, true);
        // halt($filters);
        if (isset($filters['tf_admin'])) {
            $where[] = ['tf_admin', '=', $filters['tf_admin']];
        }
        if (isset($filters['tf_status'])) {
            $where[] = ['tf_status',  '=', $filters['tf_status']];
        }
        if (isset($filters['apply_status'])) {
            $where[] = ['apply_status',  '=', $filters['apply_status']];
        }

        if (isset($filters['brand'])) {
            // $where[] = [$query_field, 'LIKE', "%{$keyword}%"];
            $where[] = ['brand',  'LIKE', $filters['brand']];
        }
        if (isset($filters['add_time'])) {
            $where[] = ['add_time',  '>=', strtotime($filters['add_time'][0])];
            $where[] = ['add_time',  '<=', strtotime($filters['add_time'][1])];
        }
        // halt($where);
        $list = $this->model
            ->where($where)
            ->order('sort desc,add_time desc')
            ->paginate($limit);
        $lists = $list->items();
        //查询admi表中的数据
        $admin = table('system_admin')->select()->toarray();
        $admin = array_column($admin, 'nickname', 'id');
        foreach ($lists as $k => $v) {
            // $lists[$k]['start_time'] = !empty($v['start_time']) ? date('Y-m-d', $v['start_time']) : '';
            // $lists[$k]['end_time'] = !empty($v['end_time']) ? date('Y-m-d', $v['end_time']) : '';
            $lists[$k]['tf_admin'] = !empty($v['tf_admin']) ? $admin[$v['tf_admin']] : '';
            $lists[$k]['tf_status'] =  $v['tf_status'] != 0 ? $this->tf_status($v['tf_status']) : '无效';
            $lists[$k]['apply_status'] =  $v['apply_status'] != 0 ? $this->apply_status($v['apply_status']) : '待审核';
            $lists[$k]['check_time'] =  !empty($v['check_time']) ? date('Y-m-d H:i:s', $v['check_time']) : '';
            $lists[$k]['add_time'] =  !empty($v['add_time']) ? date('Y-m-d H:i:s', $v['add_time']) : '';
        }
        $data = [
            'code' => 1,
            'msg' => '',
            'count' => $list->total(),
            'data' => $lists,
        ];
        return json($data);
    }
    //审核状态
    public function apply_status($status)
    {
        $apply_status = ['待审核', '审核通过', '审核不通过'];
        return  !empty($apply_status[$status]) ? $apply_status[$status] : '';
    }

    //投放状态
    public function tf_status($status)
    {
        $tf_status = ['无效', '在投', '已取消'];
        return  !empty($tf_status[$status]) ? $tf_status[$status] : '';
    }

    //投放申请
    public function tf_apply()
    {
        //brand
        $post = $this->request->post();
        $brand = strtolower($post['brand']);
        //判断当前用户是否已经在投这款产品
        $curry1_num =  table('tfrecord')->where('brand', $brand)->where('tf_admin', $this->adminId)->where('tf_status', '<>', 2)->where('apply_status', '<>', 2)->count();
        if ($curry1_num == 1) {
            return success('该编号已申请,请勿重复申请', []);
        }
        //查询当前用户所投产品的总个数
        $num =  table('tfrecord')->where('tf_admin', $this->adminId)->where('tf_status', '<>', 2)->where('apply_status', '<>', 2)->count();
        // if ($num > 3 || $num == 3) {
        //     return success('超出投放产品总数,无法投放', []);
        // }
        //当前商品是否满三个
        $curry_num =  table('tfrecord')->where('brand', $brand)->where('tf_status', '<>', 2)->where('apply_status', '<>', 2)->count();
        // if ($curry_num > 3 || $curry_num == 3) {
        //     return success('超出投放产品人数,无法投放', []);
        // }
        $time = table('product_info')->where(['brand' => $brand])->find();
        //新品期
        $xp_time = !empty($time['xp_time']) ? $time['xp_time'] : 0;
        //爆品期
        $bp_time = !empty($time['bp_time']) ? $time['bp_time'] : 0;
        $xpend_time = strtotime('+3 month', $xp_time);
        $bpend_time = strtotime('+1 month', $bp_time);
        if (time() < $xpend_time) {
            return success('新品保护期,暂无法投放', []);
        }
        if (time() < $bpend_time) {
            return success('爆品保护期,暂无法投放', []);
        }
        //查询当前用户申请
        $post['tf_admin'] = $this->adminId;
        $post['brand'] = $brand;
        $post['add_time'] = time();
        //用户id 编号  跟投开始时间 跟投结束时间
        table('tfrecord')->insert($post);
        return success('申请成功');
    }


    /**
     * 修改
     *
     */
    public function edit()
    {
        $id = input('id');
        $row = $this->model->find($id);
        if (empty($row)) {
            return error('数据不存在');
        }
        if ($this->request->isPost()) {
            $post = $this->request->post();
            //查询当前商品投放总人数
            if ($post['apply_status'] == 1) {
                $post['tf_status'] = 1;
                $post['sort'] = 999;
            }
            $post['check_time'] = time();
            // $post['start_time'] = strtotime(date('Y-m-d', strtotime($post['start_time'])) . ' 00:00:00');
            // $post['end_time'] = strtotime(date('Y-m-d', strtotime($post['end_time'])) . ' 23:59:59');
            $result = $row->save($post);
            if ($result) {
                return success('保存成功！');
            }
            return error('保存失败');
        }
        // $row['start_time'] = date('Y-m-d h:i:s', $row['start_time']);
        // $row['end_time'] = date('Y-m-d h:i:s', $row['end_time']);
        switch ($row['apply_status']) {
            case '0':
                $row['apply_status'] = '待审';
                break;
            case '1':
                $row['apply_status'] = '审核通过';
                break;
            case '2':
                $row['apply_status'] = '不通过';
                break;
            default:
                $row['apply_status'] = '';
        }

        return success('ok', $row);
    }

    public function cancel_tf()
    {
        $post = $this->request->post();
        $id = $post['id'];
        //通过id 修改状态为已取消
        table('tfrecord')->where(['id' => $id])->update(['tf_status' => 2, 'sort' => 888]);
        return success('取消成功', []);
    }
}
